﻿namespace Tszy.Unlimited.Base.Http;

/// <summary>
/// 请求参数集合。
/// </summary>
public class ResultRequestParameterCollection
{
    private readonly ResultRequestParameterCollectionDataDictionary _parameters = new();

    /// <summary>
    ///
    /// </summary>
    public ResultRequestParameterCollectionDataDictionary Parameters => _parameters;

    /// <summary>
    ///
    /// </summary>
    public int Count => _parameters.Count;

    /// <summary>
    ///
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public bool ContainsKey(string key)
    {
        if (string.IsNullOrWhiteSpace(key))
            return false;

        var targetKey = key.ToLower();

        return _parameters.ContainsKey(targetKey);
    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="key"></param>
    /// <param name="value"></param>
    public void Add(string key, string value)
    {
        if (string.IsNullOrWhiteSpace(key))
            return;

        var targetKey = key.ToLower();

        if (ContainsKey(targetKey))
        {
            _parameters[targetKey].Add(value);
        }
        else
        {
            _parameters.Add(targetKey, new ResultRequestParameterCollectionData { value });
        }
    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public string Get(string key)
    {
        if (string.IsNullOrWhiteSpace(key))
            return string.Empty;

        var targetKey = key.ToLower();

        if (!ContainsKey(targetKey))
            return string.Empty;

        return Parameters[targetKey]?.ToString() ?? string.Empty;
    }
}

/// <summary>
///
/// </summary>
public class ResultRequestParameterCollectionDataDictionary : Dictionary<string, ResultRequestParameterCollectionData>
{
    /// <summary>
    ///
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public new ResultRequestParameterCollectionData this[string key]
    {
        get
        {
            var targetKey = key?.ToLower() ?? string.Empty;

            return base[targetKey];
        }
        set
        {
            var targetKey = key?.ToLower() ?? string.Empty;
            base[targetKey] = value;
        }
    }
}

/// <summary>
///
/// </summary>
public class ResultRequestParameterCollectionData : List<string>
{
    /// <summary>
    ///
    /// </summary>
    /// <returns></returns>
    public override string ToString()
    {
        return string.Join(',', this);
    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="source"></param>
    /// <returns></returns>
    public static ResultRequestParameterCollectionData From(IEnumerable<string> source)
    {
        var data = new ResultRequestParameterCollectionData();

        if (source != null && source.Any())
            data.AddRange(source);

        return data;
    }
}
